package vn.vfriends.vbox.service.impl;

import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.vbox.model.User;
import vn.vfriends.vbox.rest.ApiConfig;
import vn.vfriends.vbox.rest.Authenticator;
import vn.vfriends.vbox.service.UserService;

/**
 *
 * @author tuancn
 */
@Stateless
public class UserServiceImpl implements UserService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    private Client client;
    
    @Inject @ApiConfig("API_URL")
    private String apiUrl;
    
    @Inject @ApiConfig("API_USER")
    private String apiUser;
    
    @Inject @ApiConfig("API_PASSWORD")
    private String apiPassword;
    
    @PostConstruct
    private void init() {
        client = ClientBuilder.newClient().register(new Authenticator(apiUser, apiPassword));
    }
    
    public UserServiceImpl() {
    }
    
    public UserServiceImpl(String apiUrl, String apiUser, String apiPassword) {
        this.apiUrl = apiUrl;
        this.apiUser = apiUser;
        this.apiPassword = apiPassword;
        client = ClientBuilder.newClient().register(new Authenticator(apiUser, apiPassword));
    }

    @Override
    public List<User> findAll() {
        WebTarget target = client.target(apiUrl + "/users");
        return target.request().get(new GenericType<List<User>>() {});
    }

    @Override
    public User create(User user) {
        WebTarget target = client.target(apiUrl + "/users");
        
        Entity<User> entity = Entity.entity(user, MediaType.APPLICATION_XML);
        return target.request().post(entity, User.class);
    }

    @Override
    public User find(Integer id) {
        WebTarget target = client.target(apiUrl + "/users")
                .path(id.toString());
        return target.request().get(User.class);
    }
    
    @Override
    public User find(String username, String provider) {
        WebTarget target = client.target(apiUrl + "/users/find")
                .queryParam("username", username).queryParam("provider", provider);
        return target.request().get(User.class);
    }
    
    @Override
    public User edit(User user) {
        WebTarget target = client.target(apiUrl + "/users");
        
        Entity<User> entity = Entity.entity(user, MediaType.APPLICATION_XML);
        return target.request().put(entity, User.class);
    }

    @Override
    public void remove(User user) {
        WebTarget target = client.target(apiUrl + "/users")
                .path(user.getId().toString());
        target.request().delete();
    }
}
